<?php
//-------------------------------------------------------------------------------------------------------
    require_once($config['jpgraph']['path'] . 'jpgraph.php');
    require_once($config['jpgraph']['path'] . 'jpgraph_stock.php');
    require_once($config['jpgraph']['path'] . 'jpgraph_line.php');
    require_once($config['jpgraph']['path'] . 'jpgraph_vector.php');
    require_once($config['jpgraph']['path'] . 'jpgraph_bar.php');
    require_once($config['jpgraph']['path'] . 'jpgraph_scatter.php');

    require_once($config['app_dir'] . '/includes/template.class.php');
    require_once($config['app_dir'] . '/classes/plot.view.php');
    //---------------------------------------------------------------------------------------------------
    class objLabelFormat {
            protected $data = false;

        public function __construct($aData) {
            $this->data = $aData;
        } //constructor

        public function format($aLabel) {
            if( $aLabel>0 )   return $this->data[$aLabel];
        } //format
    } //objLabelFomat
    //---------------------------------------------------------------------------------------------------
    class objNewsLabelFormat extends objLabelFormat {

        public function format($aLabel) {
                return $this->data[strval($aLabel)];
        } //format

    }//class NewLabelFormat
    //---------------------------------------------------------------------------------------------------
    class objStockView  extends objPlotView implements iErrorHandler, iVisible{

            protected $_disabled_vector_colors = array();
            protected $_disabled_stops_colors = array(1,2,4);
            protected $_disabled_pips_colors = array();//array(3);
            protected $_stockbar_width = 4;
            protected $_vectorarrow_size = 5;
            protected $_vectorarrow_weight = 1;//3;

            protected $_id = false;
            protected $_stocks = false;
            protected $_labels = false;
            protected $_vectors = false;
            protected $_trends = false;
            protected $_stops = false;
            protected  $_flags = false;
            //protected $_pips = false;
            protected $_stop_marks = false;
            protected $_news = false;
            protected $_scale = false;
            protected $_system = false;
            protected $year = false;

            protected $_decimal = 4;

            protected $_show_news = true;
            protected $_show_pips = true;

            protected $_flag_select_weekends = false;
            protected $_flag_divide_weeks = true;

            protected $_vector_colors = array('#708F32', '#708F32', '#E97F1B', 'red');
            protected $_legend_titles = array('#E97F1B'=>'current forecast', '#708F32'=>'correct forecast', 'red'=>'incorrect forecast');

            protected $_error_str = array('no error',
                                         'data is empty'
                                         );

        //-------------------------------------------------------------------------------------
        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        public function HideNews($aValue=true) {
            $this->_show_news = !$aValue;
        } //HideNews

        public function HidePips($aValue=true) {
            $this->_show_pips = !$aValue;
        } //HidePips

        //-------------------------------------------------------------------------------------
        public function SetData($data) {
            $this->title = $data['title'].", H4 ";
            $this->SetID($data['id']);
            $this->SetYear($data['year']);
            $this->SetStocks($data['stocks']);
            $this->SetLabels($data['labels']);
            $this->SetVectors($data['vectors']);

            $this->SetTrends($data['trends']);
            $this->SetStops($data['stops']);
            $this->SetStopMarks($data['stop_marks']);
            $this->SetPipsMarks($data['pips_marks']);
            $this->SetNews($data['news']);
            $this->SetScale($data['scale']);
            $this->SetSystem($data['system']);
            $this->SetFlags($data['flags']);

            $this->SetDecimal($data['decimal']);
        } //setData

        public function SetID($id) {
            $this->_id = $id;
        } //setID

        public function SetStocks($stocks) {
            $this->_stocks = $stocks;
        } //setStocks
        public function SetYear($year) {
            $this->year = $year;
        } //setYear

        public function SetLabels($labels) {
            $this->_labels = $labels;
        } //SetLabels

        public function SetVectors($vectors) {
            $this->_vectors = $vectors;
        } //SetVectors

        public function SetSystem($aValue) {
            $this->_system = $aValue;
        } //SetSystem

        public function SetFlags($aValue) {
            $this->_flags = $aValue;
        } //SetFlags

        public function SetTrends($trends) {
            $this->_trends = $trends;
        } //SetTrends

        public function SetStops($stops) {
            $this->_stops = $stops;
        } //SetStops

        public function SetStopMarks($aValue) {
            $this->_stop_marks = $aValue;
        } //SetStopMarks

        public function SetPipsMarks($aValue) {
            $this->_pips_marks = $aValue;
        } //SetPipsMarks

        public function SetNews($news) {
            $this->_news = $news;
        } //setNews

        public function SetForecasts($aData) {
            $this->_forecasts = $aData;
        } //setForecasts

        public function SetScale($scale) {
            $this->_scale = $scale;
        } //SetScale

        public function SetVectorColors($colors) {
            $this->_vector_colors = $colors;
        }//setVectorColors

        public function SetLegendTitles($colors) {
            $this->_legend_titles = $colors;
        }//setLegendTitles

        public function SetDecimal($aValue) {
            if( is_int($aValue) ) $this->_decimal = $aValue;
        } //SetDecimal

        public function isEmpty() {
            return empty($this->_stocks['y']);
        } //isEmpty

        public function SelectWeekends($aFlag=true) {
            $this->_flag_select_weekends = $aFlag;
        }//SelectWeekends

        public function DivideWeeks($aFlag=true) {
            $this->_flag_divide_weeks = $aFlag;
        } //DivideWeeks

        public function SetDisabledVectorColors($aColors){
            $this->_disabled_vector_colors = $aColors;
            $this->_disabled_pips_colors = array_merge($this->_disabled_pips_colors, $aColors);
        } //setDisableVectorColors

        public function SetDisabledStopsColors($aColors){
            $this->_disabled_stops_colors = $aColors;
        } //setDisableStopsColors

        public function SetDisabledPipsColors($aColors){
            $this->_disabled_pips_colors = $aColors;
        } //setDisablePipsColors
        //----------------------------------------------------------------------
        protected function BuildStocks() {
            $stockplot = new StockPlot($this->_stocks['y'], $this->_stocks['x']);
            $stockplot->SetWidth($this->_stockbar_width);
            $stockplot->SetColor('black@0.66','white@0.66','darkgray@0.66','darkgray@0.66');
            $stockplot->HideEndLines();
            $this->_graph->Add($stockplot);
        } //BuildStocks

        protected function BuildVectors() {
            if ( !empty($this->_vectors['y']) && !empty($this->_vectors['x']) ) {
                $i=0; $index=0;
                while( $i<count($this->_vectors['y'])-1 ) {
                    $x = array($this->_vectors['x'][$i], $this->_vectors['x'][$i+1]);
                    $y = array($this->_vectors['y'][$i], $this->_vectors['y'][$i+1]);
                    $i+=2;

                    if( $this->_vectors['visible'][$index] && $y[1] && $x[0] && !in_array($this->_vectors['colors'][$index], $this->_disabled_vector_colors)  ) {
                        $vectorplot = new VectorPlot($y, $x);
                        $vectorplot->arrow->SetSize($this->_vectorarrow_size);
                        $vectorplot->arrow->SetStyle('solid');
                        $vectorplot->arrow->SetWeight($this->_vectorarrow_weight);
                        $vectorplot->arrow->SetColor($this->_vector_colors[$this->_vectors['colors'][$index]-1]);
                        $this->_graph->Add($vectorplot);
                    }//if
                    //---------------------------------------------------------------------------------------------------------------------------------
                    // Show buy or sell label
                    //---------------------------------------------------------------------------------------------------------------------------------

                    $OperationLabel = new ScatterPlot(array($y[0]), array($x[0]));
                    $OperationLabel->mark->Show(false);

                    $OperationLabel->value->SetAlign('center', 'center' ); //top
                    $OperationLabel->value->SetMargin( ( 1==$this->_vectors['side'][$index] ? +1 : -1 ) * 10);
                    $OperationLabel->value->SetFont(FF_VERDANA, FS_NORMAL, 8.4);
                    $OperationLabel->value->SetFormat( ( 1==$this->_vectors['side'][$index] ? 'SELL' : 'BUY' ) );

                    //$OperationLabel->value->SetMargin( 15 );

                    $OperationLabel->value->SetColor($this->_vector_colors[$this->_vectors['colors'][$index]-1]);
                    $OperationLabel->value->Show();

                    $this->_graph->Add($OperationLabel);
                    //---------------------------------------------------------------------------------------------------------------------------------
                    // / Show buy or sell label
                    //---------------------------------------------------------------------------------------------------------------------------------
                    $index++;
                }//while
            }
        } //BuildVectors

        protected function BuildLegend() {
            $this->_graph->legend->Pos(0.02,0.02,"right","top");
            //$this->_graph->legend->SetFillColor('lightgray@0.8');
            $this->_graph->legend->SetFillColor('white@1');
            $this->_graph->legend->SetFont(FF_VERDANA, FS_NORMAL, 8);
            $this->_graph->legend->SetShadow(false);
            $this->_graph->legend->SetLineSpacing(1);
            $this->_graph->legend->SetHColMargin(2);
            $this->_graph->legend->SetFrameWeight(0);


            $ci=1;
            if ( !empty($this->_vectors['y']) && !empty($this->_vectors['x']) && !empty($this->_legend_titles))
                foreach($this->_legend_titles as $color => $title) {
                    $mark = new PlotMark();
                    $mark->SetType(MARK_FLASH);
                    $mark->SetColor($color);
                    $mark->SetFillColor($color);
                    $this->_graph->legend->Add($title, $color, $mark, 0);
                    $ci++;
                }
        } //BuildLegend

        protected function BuildTrends() {
            $index=0;
            foreach($this->_trends as $trend)
                if( !empty($trend['y']) && !empty($trend['x']) ) {
                    if( !in_array($this->_vectors['colors'][$index], $this->_disabled_vector_colors)  ) {
                        if( $trend['y'][1] ) {
                            $TrendPlot = new LinePlot($trend['y'], $trend['x']);
                            $TrendPlot->SetColor($this->_vector_colors[$this->_vectors['colors'][$index]-1]);
                            $TrendPlot->SetStyle('dashed');
                            $this->_graph->Add($TrendPlot);

                            if(  !in_array(3, $this->_disabled_vector_colors) &&
                                 3==$this->_vectors['colors'][$index] )  {
                                $TrendTitlePlot = new LinePlot(array($trend['y'][0]), array($trend['x'][0]));
                                $TrendTitlePlot->value->SetAlign('left', 'top');
                                $TrendTitlePlot->value->SetMargin(13);
                                $TrendTitlePlot->value->SetFont(FF_VERDANA, FS_NORMAL, 8);
                                $TrendTitlePlot->value->SetFormat('Target level');
                                $TrendTitlePlot->value->SetColor('black');
                                $TrendTitlePlot->value->Show();
                                $this->_graph->Add($TrendTitlePlot);
                            }//if color is 3
                        }//check for forecast without end
                    }
                    $index++;
                }

        } //BuildTrends

        protected function BuildStops() {
            $index=0;
            foreach($this->_stops as $item) {
                if( !empty($item['y']) && !empty($item['x']) && false!=$item['x']) {
                    if( 3==$this->_vectors['colors'][$index] && !in_array($this->_vectors['colors'][$index], $this->_disabled_vector_colors)  ) {

                        $StopPlot = new LinePlot($item['y'], $item['x']);
                        $StopPlot->SetColor($this->_vector_colors[$this->_vectors['colors'][$index]-1]);
                        $StopPlot->SetStyle('longdashed');
                        $this->_graph->Add($StopPlot);

                        $StopTitlePlot = new LinePlot(array($item['y'][0]), array($item['x'][0]));
                        $StopTitlePlot->value->SetAlign('left', 'top');
                        $StopTitlePlot->value->SetMargin(13);
                        $StopTitlePlot->value->SetFont(FF_VERDANA, FS_NORMAL, 8);
                        $StopTitlePlot->value->SetFormat('Stop-Loss level');
                        $StopTitlePlot->value->SetColor('black');
                        $StopTitlePlot->value->Show();
                        $this->_graph->Add($StopTitlePlot);
                    }//if color
                }//if not empty
                $index++;
            }//foreach
        } //BuildStops

        protected function BuildStopMarks() {

            foreach($this->_stop_marks as $mark)
                if( !empty($mark['y']) && !empty($mark['x']) ) {
                    if( 3!=$mark['color'] ) {
                        $MarkPlot = new LinePlot(array($mark['y'], $mark['y']), array($mark['x'], $mark['x']));

                        $MarkPlot->mark->SetType(MARK_FILLEDCIRCLE);
                        $MarkPlot->mark->SetFillColor($this->_vector_colors[$mark['color']-1]."@0.9");
                        $MarkPlot->mark->SetWidth(6);

                        $this->_graph->Add($MarkPlot);
                    }
                }
        } //BuildStopMarks
/*
        protected function BuildPipsMarks() {
            if( !$this->_show_pips ) return;

            for($mark_index=0; $mark_index<count($this->_pips_marks); $mark_index++) {

                if( $this->_pips_marks[$mark_index]['active'] )
                    $mark = $this->_pips_marks[$mark_index];
                else
                    $mark = $this->_stop_marks[$mark_index];

                if( empty($mark['y']) || empty($mark['x']) ) break;

                if( !in_array($this->_pips['color'][$index], $this->_disabled_pips_colors)  ) {
                    $PipsPlot = new ScatterPlot(array($mark['y']), array($mark['x']));
                    $PipsPlot->mark->Show(false);

                    $PipsPlot->value->SetAlign( (3==$mark['color']?'left':'right'), 'top');
                    $PipsPlot->value->SetFont(FF_VERDANA, FS_NORMAL, 8.4);
                    $PipsPlot->value->SetFormat( (3==$mark['color']?'  ':'') . (intval($mark['pip'])>0?'+':'').$mark['pip'].' pips   ');//XXX kill spaces

                    $PipsPlot->value->SetMargin( -5 );
                    if( $mark['color']>1 )$PipsPlot->value->SetColor( $this->_vector_colors[$mark['color']-1]."@0.09");
                        else $PipsPlot->value->SetColor('black');
                    $PipsPlot->value->Show();

                    $this->_graph->Add($PipsPlot);
                } //check pips color
            } //for
        } //BuildPipsMarks
*/
        protected function BuildPipsMarks() {
            if( !$this->_show_pips ) return;

            for($mark_index=0; $mark_index<count($this->_pips_marks); $mark_index++) {

                if( $this->_pips_marks[$mark_index]['active'] )
                    $mark = $this->_pips_marks[$mark_index];
                else
                    $mark = $this->_stop_marks[$mark_index];

                if( empty($mark['y']) || empty($mark['x']) ) break;

                if( !in_array($this->_pips['color'][$index], $this->_disabled_pips_colors)  ) {
                    $PipsPlot = new ScatterPlot(array($mark['y']), array($mark['x']));
                    $PipsPlot->mark->Show(false);

                    $PipsPlot->value->SetAlign( (3==$mark['color']?'left':'right'), 'top');
                    $PipsPlot->value->SetFont(FF_VERDANA, FS_NORMAL, 8.4);
                    $PipsPlot->value->SetFormat( (3==$mark['color']?'  ':'') . (intval($mark['pip'])>0?'+':'').$mark['pip'].' pips   ');//XXX kill spaces

                    $PipsPlot->value->SetMargin( -5 );
                    if( $mark['color']>1 )$PipsPlot->value->SetColor( $this->_vector_colors[$mark['color']-1]."@0.09");
                        else $PipsPlot->value->SetColor('black');
                    $PipsPlot->value->Show();

                    $this->_graph->Add($PipsPlot);
                } //check pips color
            } //for
        } //BuildPipsMarks

        protected function BuildNews() {
            if( empty($this->_news) ) return false;
                $datax = array();
                $datay = array();
                $labels = array();
                foreach($this->_news as $news) {
                       $datax[] = $news['graph']['x'];
                       $datay[] = $news['graph']['y'];
                       $labels[strval($news['graph']['y'])] = strval($news['no']);
                } //foreach
                if( empty($datax) || empty($datay) ) return false;

            //var_dump($labels);
            $LabelFormat = new objNewsLabelFormat($labels);

            $newsplot = new ScatterPlot($datay,$datax);
            $newsplot->mark->SetType(MARK_SQUARE);

            $newsplot->value->Show();
            $newsplot->value->SetColor('darkgray');
            //$newsplot->value->SetFormat('%d');

            $newsplot->value->SetFont(FF_VERDANA, FS_NORMAL, 7);
            $newsplot->value->SetFormatCallback(array($LabelFormat,'format'));//!!!!!!

            $newsplot->mark->SetColor('lightgray');
            $newsplot->mark->SetFillColor('lightgray@0.6');
            $newsplot->mark->SetWidth(15);

            $this->_graph->Add($newsplot);
            return true;
        } //BuildNews

        protected function BuildAxisX() {
            $this->_graph->xaxis->SetFont(FF_VERDANA, FS_NORMAL, 7.5);
            $this->_graph->xaxis->HideTicks(false,false);
            $this->_graph->xgrid->Show(true, false);//????
            $this->_graph->xgrid->SetLineStyle('dashed');
            $this->_graph->xaxis->scale->SetGrace(1, 0);
            $this->_graph->xgrid->SetSelectLinesX($this->_labels['xlines'], 'solid', array('lightgray@0.9', 'darkgray@0.9'));
            if( $this->_flag_divide_weeks )
                $this->_graph->xgrid->SetSelectLines2X($this->_labels['xlines2'], 'solid', 'black');

            $this->_graph->xaxis->SetMajTickPositions($this->_labels['xmajor']);
            $this->_graph->xaxis->SetLabelMargin(3);
            //$this->_graph->xaxis->SetTitleMargin(15);//!!!!!!!!!
            $this->_graph->xaxis->SetTitleMargin(9);
            $this->_graph->xaxis->title->SetFont(FF_VERDANA, FS_BOLD, 8);
            $this->_graph->xaxis->title->Set($this->year);
            //--------------------------------------------------------------------------------
            //var_dump($this->_labels['x']);
            $LabelFormat = new objLabelFormat($this->_labels['x']);
            $this->_graph->xaxis->SetLabelFormatCallback(array($LabelFormat,'format'));
            if( $this->_flag_select_weekends )
                $this->_graph->xaxis->SetSelected($this->_labels['xselected']);//!!!!!!!!!
        } //BuildAxisX

        protected function BuildAxisY() {
            $this->_graph->yaxis->SetFont(FF_VERDANA, FS_NORMAL, 7.5);
            $this->_graph->yaxis->HideTicks(false, false);
            $this->_graph->yaxis->SetLabelFormatString('%0.'.$this->_decimal.'f');
            $this->_graph->yaxis->scale->SetGrace(3, 10);

            $this->_graph->ygrid->Show(true, true);
            $this->_graph->ygrid->SetLineStyle('dashed');
            if( isset($this->_labels['y']) )
                $this->_graph->yaxis->SetTickLabels($this->_labels['y']);
        } //BuildAxisY

        protected function BuildSystem($system_text) {
            $shift = 0;

            $caption= 'intelli' ;
            $text = array();
            $text['main'] = $system_text;

            if( false!==($i=strpos(strtolower($system_text), $caption)) ) {
                $text['caption'] = trim(substr($system_text, 0, $i + strlen($caption)));
                $text['main'] = trim(substr($system_text, $i +  strlen($caption) ));
            }//

            if( $text['caption'] ) {
                $SystemLabel = new Text($text['caption'] , 10 + $shift + 1, $this->sizey - 18);
                $SystemLabel->SetFont(FF_VERDANA, FS_BOLD, 8);
                $SystemLabel->SetAlign('left', 'top');
                $SystemLabel->SetColor('#134475');
                $shift += $SystemLabel->GetWidth($this->_graph->img);

                $this->_graph->AddText($SystemLabel);
            }//caption

            $SystemLabel = new Text($text['main'], 10 + $shift + 5, $this->sizey - 18);
            $SystemLabel->SetFont(FF_VERDANA, FS_BOLD, 8);
            $SystemLabel->SetAlign('left', 'top');
            $shift += $SystemLabel->GetWidth($this->_graph->img);

            $this->_graph->AddText($SystemLabel);

        } //BuildCopyright

        protected function BuildGraph() {
          global $config;
            if ( $this->isEmpty() )  throw new Exception($this->Error(1));

            $this->_graph->SetImgFormat(strtoupper($this->type));
            if( $this->_show_logo ) $this->BuildLogo(); //Build Logo

            $this->_graph->SetAlphaBlending();
            if( $config['jpgraph']['antialiasing'] )  $this->_graph->img->SetAntiAliasing();
            $this->_graph->SetIconDepth(DEPTH_FRONT);

            $this->_graph->SetBox(false);
            $this->_graph->SetFrame(true, '#fcfcfc');

            $this->_graph->SetScale("intlin", $this->_scale['y']['min'], $this->_scale['y']['max'],
                                              $this->_scale['x']['min'], $this->_scale['x']['max']);

            $this->_graph->SetMarginColor('white');

            $this->_graph->SetMargin(45,40,55,40);//XXX increase left margin
            //$this->_graph->SetMargin(45,12,55,40);
            $this->_graph->SetTickDensity(TICKD_DENSE, TICKD_DENSE); // Many Y-ticks
            //--------------------------------------------------------------------------------
            $this->BuildAxisY();
            $this->BuildAxisX();
            //--------------------------------------------------------------------------------
            $this->BuildTitle();//add title
            if( $this->_show_copyrigth ) $this->BuildCopyright();//add copyright
            //$this->BuildStocks(); //draw stocks !!!!!!!!!!!!!!!!!!
            $this->BuildTrends(); //draw trends
            $this->BuildStopMarks(); //draw marks which point wehere forecast was closed
            $this->BuildPipsMarks();
            $this->BuildStops(); //draw stops
            $this->BuildVectors();//draw vectors
            $this->BuildLegend();//draw legend
            //var_dump($this->_system);
            if( $this->_system ) $this->BuildSystem( $this->_system['Name']);//draw title of system

            $this->BuildStocks();//!!!!!!!!!!

            //if( $this->_show_pips ) $this->BuildPips();// draw pips
            if( $this->_show_news ) $this->BuildNews();//draw fundamental news
            return true;
        } //BuildGraph

        public function RenderNews($tamplatename='_StockNewsItems.tpl') {
            $StockNewsTextView = new objStockNewsTextView($this->_id, true, $tamplatename);
            $StockNewsTextView->SetData($this->_news);
            return $StockNewsTextView->Fetch();
        } //RenderNews

    }//class objStockView
   //-------------------------------------------------------------------------------------------------------
   class objStockNewsTextView implements iDebug {
            protected $_data = false;
            protected $_template = false;

            public $id = false;
            public $force = false;
            public $templatename='_StockNewsItems.tpl';

        public function __construct($aID=false, $aForce=false, $aFilename=false) {
            $this->id = $aID;
            $this->force = $aForce;
            $this->SetTemplateName($aFileName);
            //------------------------------------------------------------------
            $this->_template = new objTemplate();
            $this->_template->caching = 2;
            $this->_template->cache_lifetime = -1;
        } //constructor

        public function SetData($aData) {
            $this->_data=$aData;
        } //SetData

        public function SetTemplateName($aFileName) {
            if( $aFileName ) $this->templatename = $aFilename;
        } //SetTemplateName

        public function isEmpty() {
            return empty($this->templatename) || ( empty($this->_data) && empty($this->id) );
        } //isEmpty

        public function Fetch($aFilename=false) {
            $this->SetTemplateName($aFileName);

            if( $this->isEmpty() )  return false;

            $id=$this->id;
            if( $id ) $id = 'news_' . $id;

            if( true===$this->force ) $this->_template->clear_cache($this->templatename, $id);
            if( !empty($this->_data) && (!true===$this->force || !$this->_template->is_cached($this->templatename, $id)) )
                $this->_template->Assign('data', $this->_data);

            return $this->_template->Fetch($this->templatename, $id);
        } //Fetch

        public function Dump() {
            echo '<br><hr><br>';
            echo '<br>id='; var_dump($this->id);
            echo '<br>force='; var_dump($this->force);
            echo '<br>templatename='; var_dump($this->templatename);
            echo '<br>data='; var_dump($this->_data);
            echo '<br><hr><br>';
        } //Dump

   } //class StockNewsTextView
   //-------------------------------------------------------------------------------------------------------
?>
